import 'package:eshi/app/shi/data/System.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class GlobalBackHandler extends StatefulWidget {
  final Widget child;


  const GlobalBackHandler({super.key, required this.child});

  @override
  _GlobalBackHandlerState createState() => _GlobalBackHandlerState();
}

class _GlobalBackHandlerState extends State<GlobalBackHandler> {
  DateTime? _lastBackPressTime;

  @override
  void initState() {
    super.initState();
    // 全局注册键盘事件
    RawKeyboard.instance.addListener(_handleGlobalKeyEvent);
  }

  @override
  void dispose() {
    RawKeyboard.instance.removeListener(_handleGlobalKeyEvent);
    super.dispose();
  }

  void _handleGlobalKeyEvent(RawKeyEvent event) async {
    // 检测 Esc 键按下
    if (event is RawKeyDownEvent && 
        event.logicalKey == LogicalKeyboardKey.escape) {

      // 尝试返回上一页
      // Navigator.of(context).maybePop();
    }
  }

  @override
  Widget build(BuildContext context) {
    // if(true) return widget.child;
    return 
    WillPopScope(
      // 拦截返回事件的回调函数
      onWillPop: () async {
           // 获取当前时间
        final now = DateTime.now();
        
        // 检查是否在2秒内再次点击了返回键
        if (_lastBackPressTime != null && 
            now.difference(_lastBackPressTime!) < const Duration(seconds: 2)) {
          // 2秒内再次点击，确认退出应用
          return true;
        }
        
        // 首次点击，记录时间并显示提示
        _lastBackPressTime = now;
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('再按一次返回键退出应用'),
            duration: Duration(seconds: 2), // 提示显示2秒
            behavior: SnackBarBehavior.floating, // 悬浮样式，不遮挡内容
          ),
        );
        
        // 不退出应用
        return false;
      },
      child: widget.child,
    );
  }
}



class KeyboardEventListener extends StatefulWidget {
  Widget? child;
  KeyboardEventListener({super.key,this.child});

  @override
  State<KeyboardEventListener> createState() => _KeyboardEventListenerState();
}

class _KeyboardEventListenerState extends State<KeyboardEventListener> with WidgetsBindingObserver {
  // 记录键盘是否弹出
  bool _isKeyboardVisible = false;
  // 记录屏幕原始高度（无键盘时）

  @override
  void initState() {
    super.initState();
    // 注册应用生命周期观察者
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    // 移除观察者
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  // 监听应用生命周期变化（包括布局变化）
  @override
  void didChangeMetrics(){
    super.didChangeMetrics();
    // 获取当前屏幕高度
    setState(() {
      _isKeyboardVisible = !_isKeyboardVisible;  
    });
    // 触发键盘状态变化回调
    if (_isKeyboardVisible) {
      _onKeyboardOpened();
    } else {
      _onKeyboardClosed();
    }
    delayCheck(500);
  }
  get time => DateTime.now().millisecondsSinceEpoch;
  void delayCheck(ms) async{
    await Future.delayed(Duration(milliseconds: ms));
    // 判断键盘是否弹出：屏幕高度减少超过50像素视为键盘弹出
    final isKeyboardVisible = MediaQuery.of(context).viewInsets.bottom>0; // _originalScreenHeight! - currentScreenHeight > 50;
    if (isKeyboardVisible != _isKeyboardVisible) {
      setState(() {
        _isKeyboardVisible = isKeyboardVisible;
      });
      
      // 触发键盘状态变化回调
      if (_isKeyboardVisible) {
        _onKeyboardOpened();
      } else {
        _onKeyboardClosed();
      }
    }
  }
  // 键盘弹出时的处理
  void _onKeyboardOpened() {
    System.onKeyboardOpenedChange(isOpen: true);
    debugPrint("软键盘已弹出");
    // 可在这里处理逻辑，如滚动列表、调整布局等
  }

  // 键盘收起时的处理
  void _onKeyboardClosed() {
    System.onKeyboardOpenedChange(isOpen: false);
    debugPrint("软键盘已收起");
    // 可在这里恢复布局等
  }

  @override
  Widget build(BuildContext context) {
    if(widget.child!=null) {
      return widget.child!;
    }
    return  Scaffold(
      appBar: AppBar(title: const Text("软键盘事件监听")),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [       
            TextField(
              decoration: const InputDecoration(
                hintText: "点击输入框弹出键盘",
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 20),
            Text(
              "键盘状态：${_isKeyboardVisible ? "已弹出" : "已收起"}",
              style: TextStyle(
                fontSize: 18,
                color: _isKeyboardVisible ? Colors.blue : Colors.grey,
              ),
            ),
          ],
        ),
      ),
    );
  }
}